package com.zqz.admin.server.service.impl;

import com.zqz.admin.server.constants.UserConstants;
import com.zqz.admin.server.dao.UserDao;
import com.zqz.admin.server.dto.UserDto;
import com.zqz.admin.server.model.User;
import com.zqz.admin.server.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger log = LoggerFactory.getLogger("adminLogger");

    @Autowired
    private UserDao userDao;

    @Override
    @Transactional//给该方法配置事务
    public User saveUser(UserDto userDto) {
        User user = userDto;
        user.setSalt(DigestUtils.md5Hex(UUID.randomUUID().toString()+System.currentTimeMillis()+UUID.randomUUID().toString()));
        user.setPassword(passwordEncoder(user.getPassword(),user.getSalt()));
        user.setStatus(User.Status.VALID);
        userDao.save(user);
        saveUserRoles(user.getId(),userDto.getRoleIds());
        log.debug("新增用户{}",user.getUsername());
        return user;
    }

    private void saveUserRoles(Long userId, List<Long> roleIds){
      if (roleIds != null){
          userDao.deleteUserRole(userId);
          if (!CollectionUtils.isEmpty(roleIds)){
              userDao.saveUserRoles(userId,roleIds);
          }
      }
    }

    @Override
    public User updateUser(UserDto userDto) {
        return null;
    }

    @Override
    public String passwordEncoder(String credentials, String salt) {
        Object object = new SimpleHash("MD5", credentials, salt, UserConstants.HASH_ITERATIONS);
        return object.toString();
    }

    @Override
    public User getUser(String username) {
        return userDao.getUser(username);
    }

    @Override
    public void changePassword(String username, String oldPassword, String newPassword) {

    }
}
